<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.8/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">

                        <div class="layui-inline">
                            <label class="layui-form-label">栏目</label>
                            <div class="layui-input-inline" id="id_div_menu_select">
                                加载中...
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">类型</label>
                            <div class="layui-input-inline" id="id_div_type_select">
                                加载中...
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline" id="id_div_status_select">
                                加载中...
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">标题</label>
                            <div class="layui-input-inline">
                                <input type="text" name="like_with_title" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">显示删除</label>
                            <div class="layui-input-inline">
                                <input type="checkbox" name="null_with_deleted_at" lay-skin="switch" lay-text="不显示删除|显示删除" value="1" checked="checked" class="layui-input" />
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">锁定</label>
                            <div class="layui-input-inline">
                                <input type="checkbox" name="locked_by" lay-skin="switch" lay-text="全部条目|被我测定" value="1" checked="checked" class="layui-input" />
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">ID</label>
                            <div class="layui-input-inline">
                                <input type="text" name="id" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="resume"><i class="layui-icon layui-icon-refresh"></i>恢复</a>
        </script>

    </div>
</div>
<script src="/lib/layui-v2.6.8/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=2.0.0" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'miniTab'], function () {
        var $ = layui.jquery,
            form = layui.form,
            layer = layui.layer,
            miniTab = layui.miniTab,
            table = layui.table;

        let currentAdminUserId = 0;
        $.get('/admin/user/getCurrent', {}, function (re) {
            if (re.code == 0) {
                currentAdminUserId = re.data.id;
                layui.use('watermark', function (watermark) {
                    watermark({watermark_txt: re.data.name});
                });
            }
        }, 'json');

        layui.createByTypeId = function (typeId) {
            $.post('/admin/item/create', {'type_id': typeId}, function (re) {
                if (re.code == 0) {
                    miniTab.openNewTabByIframe({
                        href: 'page/admin/item/edit_' + typeId + '.html#/id=' + re.data.new_id,
                        title: types[typeId] + ' # ' + re.data.new_id,
                    });
                    table.reload('currentTableId');
                    return false;
                } else {
                    layer.alert(re.msg);
                }
            }, 'json');
        };

        layui.setLock = function (id, lock) {
            $.post('/admin/item/setLock', {
                'id': id,
                'lock': lock
            }, function (re) {
                if (re.code == 0 && re.data.rows_count == 1) {
                    layer.msg((lock == 0 ? '解锁' : '锁定') + '成功');
                    table.reload('currentTableId');
                } else {
                    layer.msg((lock == 0 ? '解锁' : '锁定') + '失败 ! ' + re.msg);
                }
            });
        };

        layui.changeStatus = function (id, status) {
            $.post('/admin/item/update', {'id': id, 'status': status}, function (re) {
                if (re.code == 0) {
                    layer.msg('更新成功');
                } else {
                    layer.msg(re.msg);
                    table.reload('currentTableId');
                }
            }, 'json');
        };

        let loading = layer.load(2);

        let allStatus = [];
        $.get('/admin/item/getAllStatus', {}, function (re) {
            if (re.code == 0) {
                let allStatusOptions = '';
                for (let i in re.data) {
                    allStatusOptions += '<option value="' + i + '">' + re.data[i] + '</option>';
                }
                $('#id_div_status_select').html('<select name="status" class="layui-select"><option value="">-- 选择 --</option>' + allStatusOptions + '</select>');
                allStatus = re.data;
                form.render();
            } else {
                layer.msg('加载状态失败!');
            }
        }, 'json');

        let types = [];
        $.get('/admin/item/getAllTypes', {}, function (re) {
            if (re.code == 0) {
                types = re.data;
                let buttons = '';
                let select = '<select name="type_id" class="layui-select"><option value="">-- 选择 --</option>';
                for (let i in types) {
                    buttons += '<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="javascript:layui.createByTypeId(' + i + ');"><i class="layui-icon layui-icon-add-1"></i>' + types[i] + '</button>';
                    select += '<option value="' + i + '">' + types[i] + '</option>';
                }
                buttons += '<button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> <i class="layui-icon layui-icon-delete"></i>删除 </button>';
                buttons += '<button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="resume"> <i class="layui-icon layui-icon-refresh"></i>恢复 </button>';
                select += '</select>';
                $('#id_div_type_select').html(select);
                table.render({
                    elem: '#currentTableId',
                    url: '/admin/item/list',
                    where: {
                        null_with_deleted_at: '1',
                        order: 'top_number desc,sort_number desc,created_at desc',
                        main_id: '0'
                    },
                    done: function () {
                        $('body, html').animate({
                            scrollTop: 0
                        }, 100);
                    },
                    toolbar: '<div>' + buttons + '</div>',
                    cols: [[
                        {type: "checkbox", width: 50},
                        {field: 'id', width: 60, title: 'ID', sort: true},
                        {field: 'menu_name', width: 120, title: '栏目'},
                        {field: 'type_name', width: 120, title: '类型'},
                        {field: 'title', title: '标题', templet: function (row) {
                            let title = row.title;
                            if (row.deleted_at) {
                                title = '<span style="color: red;">(删)</span> ' + title;
                            }
                            return title;
                        }},
                        {field: 'sort_number', width: 80, title: '<i class="layui-icon layui-icon-edit"></i>排序', edit: 'text'},
                        {field: 'top_number', width: 80, title: '<i class="layui-icon layui-icon-edit"></i>置顶', edit: 'text'},
                        {title: '<i class="layui-icon layui-icon-edit"></i>状态', width: 100, templet: function (row) {
                            let allStatusOptions = '';
                            for (let i in allStatus) {
                                let selected = '';
                                if (i == row.status) {
                                    selected = ' selected';
                                }
                                allStatusOptions += '<option value="' + i + '"' + selected + '>' + allStatus[i] + '</option>';
                            }
                            if (row.locked_by_admin == '' || row.locked_by == currentAdminUserId) {
                                return '<select lay-ignore onchange="javascript:layui.changeStatus(' + row.id + ', this.value);">' + allStatusOptions + '</select>';
                            }
                            return '<select lay-ignore disabled>' + allStatusOptions + '</select>';
                        }},
                        {title: '锁定', width: 85, templet: function (row) {
                                if (row.locked_by_admin == '') {
                                    return '<button class="layui-btn layui-btn-primary layui-btn-xs" onclick="javascript:layui.setLock(' + row.id + ', 1);" title="点击锁定"><i class="fa fa-unlock"></i></button>';
                                }
                                if (row.locked_by == currentAdminUserId) {
                                    return '<button class="layui-btn layui-btn-primary layui-btn-xs" onclick="javascript:layui.setLock(' + row.id + ', 0);" title="点击解锁"><i class="fa fa-unlock-alt"></i></button>';
                                }
                            return '<i class="fa fa-lock"></i> ' + row.locked_by_admin;
                        }},
                        {title: '操作', toolbar: '#currentTableBar', width: 210}
                    ]],
                    limits: [50, 100],
                    limit: 50,
                    page: true,
                    skin: 'line'
                });
                $.get('/admin/menu/getAllAsSelect', {}, function (re) {
                    if (re.code == 0) {
                        let select = '<select name="menu_id" class="layui-select"><option value="">-- 选择 --</option>';
                        select += '<option value="0">' + (re.data.length == 0 ? '└─' : '├─') + ' 未归类文章</option>';
                        for (let i in re.data) {
                            select += '<option value="' + re.data[i].id + '">' + re.data[i].name + '</option>';
                        }
                        select += '</select>';
                        $('#id_div_menu_select').html(select);
                        form.render();
                    } else {
                        layer.alert('栏目选择下拉框加载失败！');
                    }
                }, 'json');
                form.render();
            } else {
                layer.alert('类型加载失败，不能继续操作！');
            }
            layer.close(loading);
        }, 'json');

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            if (undefined === data.field.null_with_deleted_at) {
                data.field.null_with_deleted_at = '';
            }
            if (undefined === data.field.locked_by) {
                data.field.locked_by = currentAdminUserId;
            } else {
                data.field.locked_by = '';
            }
            table.reload('currentTableId', {
                page: {curr: 1},
                where: data.field
            });
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            let checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            let ids = [];
            for (let i in data) {
                if (data[i].locked_by == 0 || data[i].locked_by == currentAdminUserId) {
                    ids.push(data[i].id);
                }
            }
            if (ids.length == 0) {
                return false;
            }
            if (obj.event === 'delete') {  // 监听删除操作
                layer.confirm('真的批量删除么？', function (index) {
                    $.post('/admin/item/deleteMulti', {'ids': ids.join(',')}, function (re) {
                        if (re.code == 0) {
                            table.reload('currentTableId');
                        } else {
                            layer.msg(re.msg);
                        }
                        layer.close(index);
                    }, 'json');
                });
            } else if (obj.event === 'resume') {
                layer.confirm('真的批量删除么？', function (index) {
                    $.post('/admin/item/resumeMulti', {'ids': ids.join(',')}, function (re) {
                        if (re.code == 0) {
                            table.reload('currentTableId');
                        } else {
                            layer.msg(re.msg);
                        }
                        layer.close(index);
                    }, 'json');
                });
            }
        });

        table.on('tool(currentTableFilter)', function (obj) {
            let data = obj.data;
            if (data.locked_by != 0 && data.locked_by != currentAdminUserId) {
                layer.msg('被其他用户锁定, 不能操作 !');
                return false;
            }
            if (obj.event === 'edit') {
                miniTab.openNewTabByIframe({
                    href: 'page/admin/item/edit_' + data.type_id + '.html#/id=' + data.id,
                    title: types[data.type_id] + ' # ' + data.id,
                });
                return false;
            } else if (obj.event === 'delete') {
                if (obj.data.deleted_at) {
                    return false;
                }
                layer.confirm('真的删除么？', function (index) {
                    obj.update({
                        deleted_at: '刚刚',
                        title: obj.data.title
                    });
                    layer.close(index);
                    $.post('/admin/item/delete', {'id': data.id}, function (re) {
                        if (re.code != 0) {
                            layer.msg(re.msg);
                        }
                    }, 'json');
                });
            } else if (obj.event === 'resume') {
                if (!obj.data.deleted_at) {
                    return false;
                }
                layer.confirm('真的恢复么？', function (index) {
                    layer.close(index);
                    obj.update({
                        deleted_at: '',
                        title: obj.data.title
                    });
                    $.post('/admin/item/resume', {'id': data.id}, function (re) {
                        if (re.code != 0) {
                            layer.msg(re.msg);
                        }
                    }, 'json');
                });
            }
        });

        // 监听单元格编辑
        table.on('edit(currentTableFilter)', function(obj) {
            let field = obj.field;
            let id = obj.data.id;
            if (obj.data.locked_by != 0 && obj.data.locked_by != currentAdminUserId) {
                layer.msg('被其他用户锁定, 不能操作 !');
                table.reload('currentTableId');
                return false;
            }
            let newValue = obj.value.trim();
            if (newValue == '' || isNaN(newValue) || id <= 0 || !(field == 'sort_number' || field == 'top_number')) {
                layer.msg('数据错误！');
                table.reload('currentTableId');
                return false;
            }
            let data = {'id': id};
            if (field == 'sort_number') {
                data['sort_number'] = newValue;
            } else {
                data['top_number'] = newValue;
            }
            $.post('/admin/item/update', data, function (re) {
                if (re.code == 0) {
                    layer.msg('更新成功');
                } else {
                    layer.msg(re.msg);
                    table.reload('currentTableId');
                }
            }, 'json');
        });

    });
</script>

</body>
</html>